package com.hxd.charitysystem.ui.activity

import android.graphics.drawable.Drawable
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.support.v7.widget.LinearLayoutManager
import android.view.View
import android.widget.LinearLayout
import com.hjq.base.BaseFragmentAdapter
import com.hxd.charitysystem.R
import com.hxd.charitysystem.adapter.DrawerAdapter
import com.hxd.charitysystem.adapter.SimpleItem
import com.hxd.charitysystem.adapter.SpaceItem
import com.hxd.charitysystem.base.common.MyActivity
import com.hxd.charitysystem.base.common.MyLazyFragment
import com.hxd.charitysystem.bean.UserInfoBean
import com.hxd.charitysystem.image.ImageLoader
import com.hxd.charitysystem.ui.fragment.*
import com.hxd.charitysystem.utils.L
import com.hxd.charitysystem.utils.ProjectUrl
import com.hxd.tabactivityfragment.util.GsonToBean
import com.hxd.tabactivityfragment.util.ThreadUtil
import com.kongzue.dialog.interfaces.OnDialogButtonClickListener
import com.kongzue.dialog.v3.MessageDialog
import com.kymjs.rxvolley.client.HttpCallback
import com.kymjs.rxvolley.client.HttpParams
import com.vondear.rxtool.RxSPTool
import com.xuexiang.xui.utils.ThemeUtils
import com.xuexiang.xui.utils.ViewUtils
import com.xuexiang.xutil.resource.ResUtils
import com.yarolegovich.slidingrootnav.SlidingRootNav
import com.yarolegovich.slidingrootnav.SlidingRootNavBuilder
import com.yarolegovich.slidingrootnav.callback.DragStateListener
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.menu_left_drawer.*
import org.jetbrains.anko.startActivity
import java.util.*


open class MainActivity : MyActivity(), DrawerAdapter.OnItemSelectedListener {


    private val POS_HOME = 0
    private val POS_MESSAGE = 1
    private val POS_QUESTION = 2
    private val POS_CONNECTION = 3
    private val POS_SETTING = 5
    private val POS_UPDATE_APP = 6
    private val POS_SHARE = 7

    private val mMenuTitles by lazy { loadMenuTitles() }
    private val mMenuIcons by lazy { loadMenuIcons() }
    private var mAdapter: DrawerAdapter? = null
    private var mSlidingRootNav: SlidingRootNav? = null
    private var mLLMenu: LinearLayout? = null

    private val mPagerAdapter by lazy { BaseFragmentAdapter<MyLazyFragment<MainActivity>>(this) }

    private var token:String = ""

    override fun getLayoutId(): Int {
        return R.layout.activity_main
    }

    override fun getTitleId(): Int {
        return R.id.tb_main_title
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initSlidingMenu(savedInstanceState)
//        EventBus.getDefault().register(this)
    }

    override fun onLeftClick(v: View?) {
        openMenu()
        log("打开了Menu")
    }

    override fun initView() {

    }

    /**
     * 初始化PagerAdapter
     */
    override fun initData() {
        mPagerAdapter.addFragment(HomeFragment.newInstance())
        mPagerAdapter.addFragment(MessageFragment.newInstance())
        mPagerAdapter.addFragment(PersonalFragment.newInstance())
        mPagerAdapter.addFragment(ConnectionFragment.newInstance())
        mPagerAdapter.addFragment(SettingFragment.newInstance())
        viewPager_main.adapter = mPagerAdapter
        // 限制页面数量
        viewPager_main.offscreenPageLimit = mPagerAdapter.count


    }

    /**
     * 实现键盘返回监听抽屉
     */
    override fun onBackPressed() {
        closeMenu()
    }

    override fun isSupportSwipeBack(): Boolean {
        // 不使用侧滑功能
        return !super.isSupportSwipeBack()
    }


    fun openMenu() {
        if (mSlidingRootNav != null) {
            mSlidingRootNav?.openMenu()
        }
    }

    fun closeMenu() {
        if (mSlidingRootNav != null) {
            mSlidingRootNav?.closeMenu()
        }
    }

    fun isMenuOpen(): Boolean? {
        return if (mSlidingRootNav != null) {
            mSlidingRootNav?.isMenuOpened
        } else false
    }

    /**
     * 初始化SlidingMenu
     */
    private fun initSlidingMenu(savedInstanceState: Bundle?) {

        mSlidingRootNav = SlidingRootNavBuilder(this)
            .withMenuOpened(false)
            .withContentClickableWhenMenuOpened(false)
            .withSavedState(savedInstanceState)
            .withMenuLayout(R.layout.menu_left_drawer)
            .inject()

        mLLMenu = mSlidingRootNav?.layout?.findViewById(R.id.ll_menu)

        //创建适配器
        mAdapter = DrawerAdapter(
            Arrays.asList(
                createItemFor(POS_HOME)?.setChecked(true),
                createItemFor(POS_MESSAGE),
                createItemFor(POS_QUESTION),
                createItemFor(POS_CONNECTION),
                SpaceItem(32),
                createItemFor(POS_SETTING),
                createItemFor(POS_UPDATE_APP),
                createItemFor(POS_SHARE)
            )
        )
        mAdapter?.setListener(this)

        recyclerView_nav.isNestedScrollingEnabled = false
        recyclerView_nav.layoutManager = LinearLayoutManager(this)
        recyclerView_nav.adapter = mAdapter

        token = RxSPTool.getString(this, "token")

        //只有登录账号后才显示用户金额
        if (token != ""){
            loadData()
            linear_account_nav.visibility = View.VISIBLE
            btn_exit_nav.visibility = View.VISIBLE
        }else{
            linear_account_nav.visibility = View.GONE
            btn_exit_nav.visibility = View.GONE
        }

        iv_avatar.setOnClickListener {
            if (token != ""){
                //暂时不做其他操作
            }else{
                startActivity<LoginActivity>()
                closeMenu()
            }
        }

        btn_exit_nav.setOnClickListener {
            MessageDialog.show(this@MainActivity,
                "提示", "确认要登出用户？",
                "确定", "取消").onOkButtonClickListener =
                OnDialogButtonClickListener { baseDialog, v ->
                    token = ""
                    RxSPTool.remove(this@MainActivity, "token")
                    linear_account_nav.visibility = View.GONE
                    btn_exit_nav.visibility = View.GONE
                    ImageLoader.loadCircleImage(iv_avatar, R.mipmap.icon_avatar1)
                    tv_name_nav.text = "点击头像登录"
                    closeMenu()
                    false
                }
        }

        //设置默认选中第一个
        mAdapter?.setSelected(POS_HOME)
        mSlidingRootNav?.isMenuLocked = true
        mSlidingRootNav?.layout?.addDragStateListener(object : DragStateListener {
            override fun onDragStart() {
                if (mSlidingRootNav?.isMenuOpened!!) {
                    ViewUtils.fadeOut(mLLMenu, 300, null)
                } else {
                    ViewUtils.fadeIn(mLLMenu, 300, null)
                }
            }

            override fun onDragEnd(isMenuOpened: Boolean) {

            }
        })
        mLLMenu?.visibility = View.GONE
    }

    override fun onItemSelected(position: Int) {
        when (position) {
            POS_HOME -> {
                viewPager_main.setCurrentItem(0, viewPager_main.currentItem == 1)
                closeMenu()
            }
            POS_MESSAGE -> {
                viewPager_main.setCurrentItem(1, viewPager_main.currentItem == 0 || viewPager_main.currentItem == 1)
                closeMenu()
            }
            POS_QUESTION -> {
                viewPager_main.setCurrentItem(2, viewPager_main.currentItem == 1 || viewPager_main.currentItem == 3)
                closeMenu()
            }
            POS_CONNECTION -> {
                viewPager_main.setCurrentItem(3, viewPager_main.currentItem == 2 || viewPager_main.currentItem == 4)
                closeMenu()
            }
            POS_SETTING -> {
                viewPager_main.setCurrentItem(4, viewPager_main.currentItem == 3 || viewPager_main.currentItem == 5)
                closeMenu()
            }
            POS_UPDATE_APP -> {
                closeMenu()
            }
            POS_SHARE -> {
                closeMenu()
            }
        }
    }

    private fun createItemFor(position: Int): SimpleItem? {
        return SimpleItem(mMenuIcons!![position], mMenuTitles!![position])
            .withIconTint(ResUtils.getColor(R.color.gray_icon))
            .withTextTint(ResUtils.getColor(R.color.gray_icon))
            .withSelectedIconTint(ThemeUtils.resolveColor(this, R.attr.colorAccent))
            .withSelectedTextTint(ThemeUtils.resolveColor(this, R.attr.colorAccent))
    }

    private fun loadMenuTitles(): Array<String> {
        return resources.getStringArray(R.array.menu_titles)
    }

    private fun loadMenuIcons(): Array<Drawable?> {
        val ta = resources.obtainTypedArray(R.array.menu_icons)
        val icons = arrayOfNulls<Drawable>(ta.length())
        for (i in 0 until ta.length()) {
            val id = ta.getResourceId(i, 0)
            if (id != 0) {
                icons[i] = ContextCompat.getDrawable(this, id)
            }
        }
        ta.recycle()
        return icons
    }

    /**
     * 加载用户信息
     */
    private fun loadData(){
        val params = HttpParams()
        params.putHeaders("token", token)
        ProjectUrl.getUserInfo(params, object: HttpCallback(){
            override fun onSuccess(t: String?) {
                val userInfo = GsonToBean.JsonToBean<UserInfoBean>(t)
                if(userInfo.status == 200){
                    ThreadUtil.runOnMainThread(Runnable {
                        if(userInfo.msg.headerUrl != null){
                            ImageLoader.loadCircleImage(iv_avatar, ProjectUrl.getUserImage + userInfo.msg.headerUrl)
                        }
                        if(userInfo.msg.name != null){
                            tv_name_nav.text = userInfo.msg.name
                        }else{
                            tv_name_nav.text = userInfo.msg.account
                        }
                        tv_balance_nav.text = userInfo.msg.balance.toString()
                    })
                }else{
                    L.i("MainActivi用户信息获取失败： mag: ${userInfo.msg}")
                }
            }

            override fun onFailure(errorNo: Int, strMsg: String?) {
                L.i(" MainActivi errorNo : $errorNo, strMsg: $strMsg ")
            }
        })
    }

    override fun onDestroy() {
        viewPager_main.adapter = null
        super.onDestroy()
    }

    override fun onResume() {
        super.onResume()
        if(token != ""){
            loadData()
        }
    }


}
